//
//  GUID2Int.m
//  GUID2Int
//
//  Created by Lex on 2016/10/24.
//  Copyright © 2016年 Lex. All rights reserved.
//

#import "GUID2Int.h"

@implementation GUID2Int


/**
 *  GUID转为int值
 */
+(NSInteger)GetIntvalWithGUID:(NSString*) guid
{
    
    unsigned long long  intGUID=0;
    if(!(guid.length==32))
    {
        return -1;
    }
    
    NSString *item1=[guid substringWithRange:NSMakeRange(0, 8)];
    NSString *item2=[guid substringWithRange:NSMakeRange(8, 4)];
    NSString *item3=[guid substringWithRange:NSMakeRange(12, 4)];
    
    NSMutableArray *arryStrItems,*arryIntItems;
    arryStrItems=[NSMutableArray arrayWithObjects:item1,item2,item3, nil];
    arryIntItems=[NSMutableArray new];
    for (int i=0; i<arryStrItems.count; i++) {
        [arryIntItems addObjectsFromArray:
         [self Split2CharHexToIntWithString:[arryStrItems objectAtIndex:i]]
         ];
    }
    
    for (int i=0; i<arryIntItems.count; i++) {
        NSLog(@" %lld +=  %ld x %f ->(256)%d次方",intGUID,[[arryIntItems objectAtIndex:i] integerValue],pow(256, i),i);
        intGUID=(unsigned long long)intGUID+(unsigned long long)([[arryIntItems objectAtIndex:i] longLongValue]*pow(256, i));
        
    }
    
    
    NSLog(@"%lld %% 1024 = %lld",intGUID,intGUID%1024);
    
    intGUID=intGUID%1024;

    
    return intGUID;
}

/**
 *  切割字符串每2个字符成16进制并转10进制，值列表按倒序排序
 */
+(NSMutableArray*) Split2CharHexToIntWithString:(NSString*) str
{
    NSLog(@"group:%@",str);
    
    long itemLength=str.length/2;
    
    NSMutableArray *rtnArry=[NSMutableArray new];
    
    for (int i=0; i<itemLength; i++) {
        [rtnArry addObject:@"0"];
    }
    
    unsigned int outVal;
    NSScanner* scanner;
    
    NSString *indexVal;
    while (str.length>0) {
        
        indexVal=[str substringWithRange:NSMakeRange(0, 2)];
        str=[str stringByReplacingOccurrencesOfString:indexVal withString:@""];
        
        scanner = [NSScanner scannerWithString:indexVal];
        [scanner scanHexInt:&outVal];
        
        [rtnArry replaceObjectAtIndex:itemLength-1 withObject:[NSString stringWithFormat:@"%d",outVal]];
        
        itemLength--;
        
        NSLog(@"split char:%@  -> %d",indexVal,outVal);
    }
    
    NSLog(@"#DESC Int Array:\n%@",rtnArry);
    
    NSLog(@"-------------------------");
    return rtnArry;
}


@end
